import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import { deEmptyChildrenCascader, maskPhoneNumber } from '../../../../utils/hooks';
import { filterTreeToArr, judgeAuth, openAuth } from '../../../../utils/util';
const $api = require('../../../../request/api').API;

Page({
  data: {
    beeperId: '',
    parentIds: '',
    accidentAddress: {
      voiceFlag: false, // true表示是语音识别
      value: '',
      houseNumber: '' // 选中的门牌号
    },
    showHouseNumber: false,
    houseNumberList: [],
    noticeAddress: {
      title: '',
      selectList: [],
      value: '',
      columns: [], // 栋单元层门牌号列表,通知对象
      buildId: '',
      buildName: '',
      unitId: '',
      unitName: '',
      floorName: '',
      floorId: '',
      houseNumber: '' // 输入的门牌号
    },
    // 事故地点的栋单元层，门牌号
    residentAddress: {
      title: '',
      fieldNames: {
        text: 'name',
        value: 'id'
      },
      value: '',
      columns: [],
      show: false,
      multiple: false
    },
    existResidentName: '',
    userList: [],
    pageNo: 1,
    pageSize: 10,
    totalPage: 0,
    isInform: false,
    alarm: {
      show: false,
      columns: [
        {
          id: 'fire',
          name: '火警',
          imgUrl: 'http://pic.kanglailab.com/common/fire-alarm.png'
        },
        {
          id: 'gasLeak',
          name: '燃气泄露',
          imgUrl: 'http://pic.kanglailab.com/common/gas-alarm.png'
        },
        // {
        // 	id: 'soak',
        // 	name: "水浸溢水",
        // 	imgUrl: "http://pic.kanglailab.com/common/watersurface-alarm.png"
        // },
        {
          id: 'lockOpen',
          name: '被盗风险',
          imgUrl: 'http://pic.kanglailab.com/common/opendoor-alarm.png'
        },
        {
          id: 'sos',
          name: '紧急求助',
          imgUrl: 'https://pic.kanglailab.com/common/sos-alarm.png'
        },
        {
          id: 'fall',
          name: '洪涝灾害',
          imgUrl: 'https://pic.kanglailab.com/common/flood.png'
        },
        {
          id: 'liftFault',
          name: '电梯故障',
          imgUrl: 'https://pic.kanglailab.com/common/equip/lift_fault.png'
        },
        {
          id: 'waterOff',
          name: '停水',
          imgUrl: 'https://pic.kanglailab.com/common/equip/water_off.png'
        },
        {
          id: 'blackOut',
          name: '停电',
          imgUrl: 'https://pic.kanglailab.com/common/equip/black_out.png'
        },
        {
          id: 'other',
          name: '其他',
          imgUrl: 'https://pic.kanglailab.com/common/equip/other.png'
        },
        {
          id: 'activity',
          name: '活动',
          imgUrl: 'https://pic.kanglailab.com/common/equip/activity.png'
        }
      ],
      selected: undefined
    },
    remark: '',
    empty: false,
    showOverlay: false,
    navigationBarTitle: '',
    houseNumberArr: [],
    btnId: '',
    typeId: '',
    notifyShow: false,
    notifyMethod: ['1'],
    activityContent: ''
  },
  async onLoad({ beeperId, parentIds, btnId }) {
    this.recordRecognitionManager = requirePlugin('WechatSI').getRecordRecognitionManager();
    parentIds = parentIds ? parentIds.split(',') : [];
    const buildId = parentIds[0] || '';
    const unitId = parentIds[1] || '';
    const floorId = parentIds[2] || '';
    this.setData({
      notifyShow: true,
      beeperId,
      parentIds,
      btnId,
      'noticeAddress.buildId': buildId,
      'noticeAddress.unitId': unitId,
      'noticeAddress.floorId': floorId
    });
    this.getResidentAddressList();
    this.search();
    this.initRecord();
    let record = await judgeAuth('scope.record');
    if (record === undefined) {
      wx.authorize({
        scope: 'scope.record',
        success: () => {
          this.recordSoundAuth = true;
        }
      });
    } else if (!record) {
      await openAuth('scope.record');
      this.recordSoundAuth = true;
    } else {
      this.recordSoundAuth = true;
    }
  },
  //识别语音 -- 初始化
  initRecord: function () {
    // 有新的识别内容返回，则会调用此事件
    this.recordRecognitionManager.onRecognize = res => {};
    // 正常开始录音识别时会调用此事件
    this.recordRecognitionManager.onStart = res => {
      this.duringRecord = true; // 把值设置为false,表示不是进来的时候识别录音
      wx.vibrateLong();
      this.setData({
        showOverlay: true
      });
    };
    // 识别错误事件
    this.recordRecognitionManager.onError = res => {
      console.error('error msg', res);
      Toast.clear();
      this.startRecord = false;
      let msg = '语音报错';
      if (res.retcode == '-30011') {
        msg = '录制太频繁';
      } else if (!this.duringRecord) {
        // 如果this.duringRecord存在表示进来的还在识别就直接不报错了
        return;
      }
      Toast.fail(msg);
    };
    //识别结束事件
    this.recordRecognitionManager.onStop = res => {
      Toast.clear();
      this.startRecord = false;
      if (!this.duringRecord) return; // 进来的时候还在识别，那么即使是被成功也不需要了
      console.log('..............结束录音');
      console.log('录音临时文件地址 -->' + res.tempFilePath);
      console.log('录音总时长 -->' + res.duration + 'ms');
      console.log('文件大小 --> ' + res.fileSize + 'B');
      console.log('语音内容 --> ' + res.result);
      this.setData({
        'accidentAddress.value': res.result
      });
      if (res.result == '') {
        wx.showModal({
          title: '提示',
          content: '听不清楚，请重新说一遍！',
          showCancel: false,
          success: function (res) {}
        });
        return;
      }
    };
  },
  // 搜索
  search() {
    this.setData({ pageNo: 1 });
    this.getUserList();
  },
  // 获取地址列表
  async getResidentAddressList() {
    const { beeperId, parentIds } = this.data;
    let res = await $api.getResidentAddressList({
      beeperId
    });
    res = res.data.data || [];
    let houseNumberArr = [];
    res.forEach((l, indexL) => {
      if (l.children.length > 0) {
        l.children.forEach((dy, indexD) => {
          if (dy.children.length > 0) {
            dy.children.forEach((c, indexC) => {
              let copiedC = Object.assign({}, c); // 复制c对象
              houseNumberArr.push(copiedC);
              c.children = []; // 清空复制后的对象的children属性
            });
          }
        });
      }
    });
    let target = '';
    let navigationBarTitle = '物业通知';
    deEmptyChildrenCascader(res);
    const modifyData = {};
    switch (parentIds.length) {
      case 0:
        modifyData['noticeAddress.title'] = '请选择栋单元层';
        modifyData['noticeAddress.columns'] = res;
        break;
      case 1:
        modifyData['noticeAddress.title'] = '请选择单元层';
        target = filterTreeToArr(
          res,
          {
            id: parentIds[0]
          },
          'id'
        );
        modifyData['noticeAddress.columns'] = target.at(-1).children || [];
        navigationBarTitle = target.map(item => item.name).toString();
        break;
      case 2:
        modifyData['noticeAddress.title'] = '请选择层';
        target = filterTreeToArr(
          res,
          {
            id: parentIds[1]
          },
          'id'
        );
        modifyData['noticeAddress.columns'] = target.at(-1).children || [];
        navigationBarTitle = target.map(item => item.name).toString();
        break;
      case 3:
        target = filterTreeToArr(
          res,
          {
            id: parentIds[2]
          },
          'id'
        );
        navigationBarTitle = target.map(item => item.name).toString();
    }
    // wx.setNavigationBarTitle({
    //   title: navigationBarTitle,
    // })
    this.setData({
      ...modifyData,
      navigationBarTitle,
      houseNumberArr
    });
  },
  // 获取用户列表
  async getUserList() {
    let {
      pageNo,
      pageSize,
      noticeAddress: { buildId, unitId, floorId, houseNumber },
      userList,
      beeperId
    } = this.data;
    const params = {
      pageNo,
      pageSize,
      houseNumber,
      buildIds: buildId,
      unitIds: unitId,
      floorIds: floorId,
      beeperId
    };
    Toast.loading({
      message: '加载中',
      forbidClick: true,
      mask: true,
      duration: 0
    });
    let res = await $api.getResidentList(params);
    const { totalPage, list } = res.data.data;
    userList = pageNo == 1 ? list : userList.concat(list);
    this.setData({
      userList: userList.map(i => {
        return {
          ...i,
          phone: maskPhoneNumber(i.phone)
        };
      }),
      totalPage,
      empty: userList.length ? false : true
    });
    Toast.clear();
  },
  async showHouseNumberPopup(e) {
    const { floorId } = this.data.noticeAddress;
    if (!floorId) return Toast.fail('需要选到层');
    if (floorId.includes(',')) return Toast.fail('多选不能选门牌号');
    let { houseNumberArr } = this.data;
    let houseNumberList = houseNumberArr.filter(item => {
      return item.id == floorId;
    })[0].children;

    houseNumberList = houseNumberList.map(item => {
      return item.name;
    });
    this.setData({
      houseNumberList,
      showHouseNumber: true
    });
  },
  confirmHouseNumber(e) {
    this.setData({
      'noticeAddress.houseNumber': e.detail.value
    });
    this.closeHouseNumber();
  },
  closeHouseNumber() {
    this.setData({
      showHouseNumber: false
    });
  },
  // 获取门牌号列表
  async getHouserNumber(floorId) {
    let res = await $api.getHouseNumberByFloorId({
      floorId
    });
    return res.data.data || [];
  },
  onInput(e) {
    const {
      detail: { value },
      currentTarget: {
        dataset: { prop }
      }
    } = e;
    this.setData({
      [prop]: value
    });
  },
  delete(e) {
    const { prop } = e.currentTarget.dataset;
    const modifyData = {};
    let { noticeAddress } = this.data;
    switch (prop) {
      case 'noticeAddress':
        const delObj = {
          floorName: '',
          floorId: '',
          value: ''
        };
        const length = this.data.parentIds.length;
        if (length <= 1) {
          delObj.unitId = '';
          delObj.unitName = '';
        }
        if (length == 0) {
          delObj.buildId = '';
          delObj.buildName = '';
        }
        delObj.value = '';
        modifyData.noticeAddress = Object.assign(noticeAddress, delObj);
        modifyData.noticeAddress.selectList = [];
        break;
      default:
        modifyData[prop] = '';
    }
    this.setData(modifyData);
  },
  showResidentAddressPopup(e) {
    // type为1表示事故发生地，type为2表示通知对象
    // this.type = e.currentTarget.dataset.type
    const { value, columns, title } = this.data.noticeAddress;
    this.setData({
      'residentAddress.value': value,
      'residentAddress.columns': columns,
      'residentAddress.show': true,
      'residentAddress.title': title
    });
  },
  residentAddressChange(e) {
    const { selectedOptions } = e.detail;
    this.selectedOptions = selectedOptions;
    // 临时保存数据
  },
  confirmResidentAddress() {
    const { parentIds, noticeAddress } = this.data;
    if (!this.selectedOptions) return;
    const [obj1, obj2, obj3] = this.selectedOptions;
    if (!obj1) return;
    switch (parentIds.length) {
      case 0:
        noticeAddress.buildId = obj1.id;
        noticeAddress.buildName = obj1.name;
        noticeAddress.value = obj1.id;
        noticeAddress.selectList = [
          {
            buildId: obj1.id,
            buildName: obj1.name,
            name: obj1.name
          }
        ];
        if (obj2) {
          noticeAddress.unitId = obj2.id;
          noticeAddress.unitName = obj2.name;
          noticeAddress.value = obj2.id;
          Object.assign(noticeAddress.selectList[0], {
            unitId: obj2.id,
            unitName: obj2.name,
            name: obj1.name + '/' + obj2.name
          });
        } else {
          noticeAddress.unitId = '';
          noticeAddress.unitName = '';
        }
        if (obj3) {
          // 最后一级时可以多选的所以是一个数组
          let ids = [];
          let names = [];
          let tempObj = noticeAddress.selectList[0];
          obj3.forEach(({ id, name }, index) => {
            ids.push(id);
            names.push(name);
            noticeAddress.selectList[index] = {
              ...tempObj,
              floorId: id,
              floorName: name,
              name: tempObj.name + '/' + name
            };
          });
          noticeAddress.floorId = ids.toString();
          noticeAddress.floorName = names.toString();
          noticeAddress.value = ids.toString();
        } else {
          noticeAddress.floorId = '';
          noticeAddress.floorName = '';
        }
        break;
      case 1:
        noticeAddress.unitId = obj1.id;
        noticeAddress.unitName = obj1.name;
        noticeAddress.value = obj1.id;
        noticeAddress.selectList = [
          {
            unitId: obj1.id,
            unitName: obj1.name,
            name: obj1.name
          }
        ];
        if (obj2) {
          let ids = [];
          let names = [];
          let tempObj = noticeAddress.selectList[0];
          obj2.forEach(({ id, name }, index) => {
            ids.push(id);
            names.push(name);
            noticeAddress.selectList[index] = {
              ...tempObj,
              floorId: id,
              floorName: name,
              name: tempObj.name + '/' + name
            };
          });
          noticeAddress.floorId = ids.toString();
          noticeAddress.floorName = names.toString();
          noticeAddress.value = ids.toString();
        } else {
          noticeAddress.floorId = '';
          noticeAddress.floorName = '';
        }
        break;
      case 2:
        let ids = [];
        let names = [];
        obj3.forEach(({ id, name }, index) => {
          ids.push(id);
          names.push(name);
          noticeAddress.selectList[index] = {
            floorId: id,
            floorName: name,
            name: name
          };
        });
        noticeAddress.floorId = ids.toString();
        noticeAddress.floorName = names.toString();
        noticeAddress.value = ids.toString();
        break;
    }
    noticeAddress.houseNumber = '';
    this.setData({ noticeAddress });
    this.closeResidentAddress();
  },
  closeResidentAddress() {
    this.setData({
      'residentAddress.show': false
    });
  },
  // 选中
  onSelectAlarmType(e) {
    const { item } = e.currentTarget.dataset;
    const { alarm } = this.data;
    let selectTypeId = '';
    alarm.columns.forEach(item2 => {
      if (item2.id === item.id) {
        item2.selected = true;
        if (item2.selected) {
          selectTypeId = item2.id;
        } else {
          selectTypeId = '';
        }
      } else {
        item2.selected = false;
      }
    });
    this.setData({
      'alarm.columns': alarm.columns,
      typeId: selectTypeId,
      notifyShow: false,
      notifyMethod: ['1'],
      'accidentAddress.value': '',
      'alarm.selected': alarm.columns.find(c => c.id === selectTypeId)
    });
  },
  inputRemark(e) {
    this.setData({
      remark: e.detail.value
    });
  },
  async handleSend() {
    const {
      noticeAddress: { buildId, unitId, floorId, houseNumber },
      btnId,
      accidentAddress,
      beeperId,
      userList,
      alarm,
      remark,
      isInform,
      typeId,
      activityContent,
      notifyMethod
    } = this.data;
    if (typeId !== 'activity' && !accidentAddress.value) {
      Toast.fail('请先选择事故发生地的地址');
      return;
    }
    let noticeType = alarm.columns.find(item => item.selected)?.id;
    if (!noticeType) {
      Toast.fail('请选择报警类型');
      return;
    }
    if (!userList.length) {
      Toast.fail('请先搜索通知对象');
      return;
    }
    await Dialog.confirm({
      title: '提示',
      message: '确定发送？'
    });
    const params = {
      strBuildIds: buildId,
      strUnitIds: unitId,
      strFloorIds: floorId,
      houseNumber,
      beeperId,
      noticeType,
      remark,
      btnId,
      notifyWay: notifyMethod.toString(),
      notifyPmc: this.data.typeId == 'fire' ? (isInform == false ? 0 : 1) : 0
    };
    if (typeId !== 'activity') {
      params.address = accidentAddress.value;
    } else {
      params.content = activityContent;
    }

    Toast.loading({
      message: '发送中',
      duration: 0,
      forbidClick: true
    });
    await $api.notifySend(params);
    Toast.success('发送成功');
  },
  hideOverlay() {
    this.setData({
      showOverlay: false
    });
  },
  recordSound() {
    // this.selectComponent("#sound-record-two").start()
    if (!this.recordSoundAuth) return;
    this.startRecord = true;
    this.recordRecognitionManager.start({
      lang: 'zh_CN',
      duration: 10000
    });
  },
  endSound() {
    if (!this.recordSoundAuth) return;
    this.setData({
      showOverlay: false
    });
    if (this.startRecord) {
      Toast.loading({
        message: '语音识别中',
        forbidClick: true,
        mask: true,
        duration: 0
      });
      this.recordRecognitionManager.stop();
    }
  },
  openInform(e) {
    console.log(e);
    this.setData({
      isInform: e.detail
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.recordRecognitionManager.onStop = () => {};
    this.recordRecognitionManager.onError = () => {};
    this.recordRecognitionManager.onStart = () => {};
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let { totalPage, pageNo } = this.data;
    if (totalPage <= pageNo) return;
    this.setData({
      pageNo: ++pageNo
    });
    this.getUserList();
  },
  /**
   * 通知类型弹出框确认
   */
  handleSelectAlarmType() {
    this.setData({ notifyShow: true });
  },
  /**
   * 通知方式选择
   * @param event
   */
  handleNotifyMethodChange(event) {
    this.setData({ notifyMethod: event.detail });
  }
});
